package com.rabbit.example3;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

/**
 * 在exampl1 的Send 上做一点修改
 * 
 * 本例模拟一个工作队列，展示Round-robin(轮询)发送消息现象
 * 
 * 1：先运行2个接收者 
 * 2：一次发送10条消息
 * 3：查看两个接收者，接收的打印消息。我们会发现两个接收者轮流接收消息。
 * 	 打印如下 接收的是双数：
 * 	 [x] Done
 *	 [x] Received 'Hello word ! ..'
 *   [x] Done
 *	 [x] Received 'Hello word ! ....'
 *	 [x] Done
 *	 [x] Received 'Hello word ! ......'
 *	 [x] Done
 *	 [x] Received 'Hello word ! ........'
 *	 [x] Done
 *  接收的是单数
 *   [x] Received 'Hello word ! .'
 *   [x] Done
 *   [x] Received 'Hello word ! ...'
 *   [x] Done
 *   [x] Received 'Hello word ! .....'
 *   [x] Done
 *   [x] Received 'Hello word ! .......'
 *   [x] Done
 *   [x] Received 'Hello word ! .........'
 *   [x] Done
 * 
 * 
 * @author dell
 *
 */
public class NewTask {
	private static final String QUEUE_NAME = "task_queue";
	private static final String HOST = "192.168.21.135";
	private static final int PORT = 5672;
	private static final String USERNAME = "ceshi";
	private static final String PASSWORD = "123456";
	private static final String VIRTUALHOST = "/";

	public static void main(String[] args) throws IOException, TimeoutException {

		// <1>创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		// <2>指定连接的broker Server地址，以及联接用户名和virtualhost
		factory.setHost(HOST);
		factory.setPort(PORT);
		factory.setUsername(USERNAME);
		factory.setPassword(PASSWORD);
		factory.setVirtualHost(VIRTUALHOST);

		// <3>与broker建立tcp联接。
		Connection connection = factory.newConnection();
		// <4>在tcp联接上建立通道，通道可以建立多个
		Channel channel = connection.createChannel();
		// <5>通道上声明队列
		channel.queueDeclare(QUEUE_NAME, // 队列名称
				false, // 消息是否持久化
				false, // 队列是否由该通道独占，意思是基他的channel不能声明该queue,即不能使用其发送消息
				false, // 消息是否自动删除
				null);// queue的一些其他的属性

		// 
		String delimiter = ".";
		String text = "Hello word ! ";
		for (int i = 0; i < 10; i++) {
			StringBuilder words = new StringBuilder(text);
			for (int j = 1; j <= i; j++) {
				words.append(delimiter);
			}
			String Message = words.toString();

			// <6>发送消息
			channel.basicPublish("", // 使用默认的exchange
					QUEUE_NAME, // routekey 就使用队列名称
					MessageProperties.PERSISTENT_TEXT_PLAIN, // 基本属性为null
					Message.getBytes());// 消息内容
			System.out.println("[x] Send: '" + Message + "' ");
		}

		// <7>关闭通道和连接
		channel.close();
		connection.close();

		// <8>消息发送后，我们可去rabbitmq server中的 queue标签下看到 Name 为queue的 Ready列的值为1.
		// 说明有一条消息，在上面，这时我们可以点击 hello 看消息详情。
	}

}
